//! 应用管理器模块
//! 
//! 提供应用的生命周期管理功能

use crate::utils::error::{YayaError, Result};

/// 应用状态
#[derive(Debug, Clone, PartialEq)]
pub enum AppState {
    Created,    // 已创建
    Running,    // 运行中
    Paused,     // 暂停
    Stopped,    // 停止
}

/// 应用信息
pub struct AppInfo {
    pub name: String,
    pub version: String,
    pub entry_point: usize,
    pub state: AppState,
}

/// 应用管理器
pub struct ApplicationManager {
    applications: Vec<AppInfo>,
    current_app: Option<usize>,
}

impl ApplicationManager {
    /// 创建新的应用管理器
    pub fn new() -> Result<Self, YayaError> {
        Ok(ApplicationManager {
            applications: Vec::new(),
            current_app: None,
        })
    }
    
    /// 初始化应用管理器
    pub fn init() -> Result<(), YayaError> {
        info!("初始化应用管理器");
        Ok(())
    }
    
    /// 关闭应用管理器
    pub fn shutdown() -> Result<(), YayaError> {
        info!("关闭应用管理器");
        Ok(())
    }
    
    /// 注册应用
    pub fn register_application(&mut self, name: &str, version: &str, entry_point: usize) -> Result<usize, YayaError> {
        let app_id = self.applications.len();
        
        let app_info = AppInfo {
            name: name.to_string(),
            version: version.to_string(),
            entry_point,
            state: AppState::Created,
        };
        
        self.applications.push(app_info);
        info!("注册应用: {} v{}", name, version);
        
        Ok(app_id)
    }
    
    /// 启动应用
    pub fn start_application(&mut self, app_id: usize) -> Result<(), YayaError> {
        if let Some(app) = self.applications.get_mut(app_id) {
            app.state = AppState::Running;
            self.current_app = Some(app_id);
            info!("启动应用: {}", app.name);
            Ok(())
        } else {
            Err(YayaError::InvalidParameter("应用不存在".into()))
        }
    }
    
    /// 停止应用
    pub fn stop_application(&mut self, app_id: usize) -> Result<(), YayaError> {
        if let Some(app) = self.applications.get_mut(app_id) {
            app.state = AppState::Stopped;
            if self.current_app == Some(app_id) {
                self.current_app = None;
            }
            info!("停止应用: {}", app.name);
            Ok(())
        } else {
            Err(YayaError::InvalidParameter("应用不存在".into()))
        }
    }
    
    /// 获取当前运行的应用
    pub fn get_current_application(&self) -> Option<&AppInfo> {
        self.current_app.and_then(|id| self.applications.get(id))
    }
    
    /// 获取所有应用信息
    pub fn get_applications(&self) -> &[AppInfo] {
        &self.applications
    }
}